<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Title</title>
</head>
<body>
<div id="app">
    <h1>{{weibo.author}}说:{{weibo.content}}</h1>
    <p>发布于:{{weibo.created}}</p>
    <img :src="weibo.url"  width="500" alt="">
    <hr>
    <h2>相关评论</h2>
    <div v-for="comment in arr">
        <h4>{{comment.author}}说:{{comment.content}}</h4>
        <p>发布于:{{comment.created}}</p>
        <hr>

    </div>
    <form action="">
        <input type="text" name="content" placeholder="写点评论...">
        <input type="button" value="评论" @click="comment()">
    </form>
</div>
<!--引入Vue-->
<script src="https://cdn.jsdelivr.net/npm/vue@2/dist/vue.js"></script>
<!--引入Axios-->
<script src="https://unpkg.com/axios/dist/axios.min.js"></script>
<!--引入处理时间格式的js文件-->
<script src="http://cdn.staticfile.org/moment.js/2.24.0/moment.js"></script>
<script>
    let vm = new Vue({
        el : "#app",
        data:{
            weibo:{},
            arr:[]//装所有评论的数组
        },
        created:function () {
            /*从请求地址栏中得到id
            * 向/selectById?id=xxx发出请求 把得到的数据给到weibo对象
            * 页面会自动显示*/
            let id = location.search.split("=")[1];
            axios.get("/selectById?id="+id).then(function (response) {
                vm.weibo = response.data;
                //转换时间格式
                vm.weibo.created = moment(vm.weibo.created).
                format("YYYY年MM月DD日 HH时mm分ss秒")

            })
            //发请求获取和当前微博相关的所有评论信息
            axios.get("/comment/selectByWeiboId?id="+id).then(function (response) {
                vm.arr = response.data;
                for (let comment of vm.arr){
                    comment.created = moment(comment.created).
                    format("YYYY年MM月DD日 HH时mm分ss秒")
                }

            })

        },
        methods:{
            comment :function () {
                let data = new FormData(document.querySelector("form"));
                //判断用户输入的内容为空字符串,为空不能发布
                if (data.get("content")==""){
                    alert("评论内容不能为空!")
                    return ;
                }
                /*往data里面添加一个微博Id的参数
                * 从请求地址栏中得到微博Id*/
                let id = location.search.split("=")[1];
                data.set("weiboId",id);

                axios.post("/comment",data).then(function (response) {
                        if (response.data==1){
                            alert("评论完成!");
                            location.reload();
                        }else {
                            alert("请您先登录后在评论!");
                            location.href = "/login.html";
                        }
                })

            }
        }
    })
</script>
</body>
</html>